package com.nanjia.boot.warehouse.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.warehouse.converter.WarehouseConverter;
import com.nanjia.boot.warehouse.mapper.WarehouseMapper;
import com.nanjia.boot.warehouse.model.entity.Warehouse;
import com.nanjia.boot.warehouse.model.form.WarehouseForm;
import com.nanjia.boot.warehouse.model.query.WarehouseQuery;
import com.nanjia.boot.warehouse.model.vo.WarehouseVO;
import com.nanjia.boot.warehouse.service.WarehouseService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 仓库信息服务实现类
 *
 * @author 周洋
 * @since 2025-07-04 15:08
 */
@Service
@RequiredArgsConstructor
public class WarehouseServiceImpl extends ServiceImpl<WarehouseMapper, Warehouse> implements WarehouseService {

    private final WarehouseConverter warehouseConverter;

    private final WarehouseMapper warehouseMapper;

    /**
     * 获取仓库信息分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<WarehouseVO>} 仓库信息分页列表
     */
    @Override
    public IPage<WarehouseVO> getWarehousePage(WarehouseQuery queryParams) {
        Page<WarehouseVO> pageVO = this.baseMapper.getWarehousePage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取仓库信息表单数据
     *
     * @param id 仓库信息ID
     * @return 仓库信息表单数据
     */
    @Override
    public WarehouseForm getWarehouseFormData(Long id) {
        Warehouse entity = this.getById(id);
        return warehouseConverter.toForm(entity);
    }

    /**
     * 新增仓库信息
     *
     * @param formData 仓库信息表单对象
     * @param ipAddr
     * @return 是否新增成功
     */
    @Override
    public boolean saveWarehouse(WarehouseForm formData, String ipAddr) {
        LambdaQueryWrapper<Warehouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Warehouse::getId);
        List<Warehouse> list = this.list(queryWrapper);
        int x = 0;
        if (CollectionUtils.isNotEmpty(list)) {
            x = Integer.parseInt(list.get(0).getWarehouseSn());
        }
        Warehouse entity = warehouseConverter.toEntity(formData);
        entity.setWarehouseSn(String.format("%04d", x + 1));
        entity.setCreateTime(LocalDateTime.now());
        entity.setCreateIp(ipAddr);
        entity.setCreateBy(SecurityUtils.getUserStrId());
        return this.save(entity);
    }

    /**
     * 更新仓库信息
     *
     * @param id       仓库信息ID
     * @param formData 仓库信息表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateWarehouse(Long id, WarehouseForm formData) {
        Warehouse entity = warehouseConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除仓库信息
     *
     * @param ids 仓库信息ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteWarehouses(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的仓库信息数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        List<Warehouse> list = new ArrayList<>();
        for (Long l : idList) {
            Warehouse warehouse = new Warehouse();
            warehouse.setId(l);
            warehouse.setUpdateTime(LocalDateTime.now());
            warehouse.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
            warehouse.setWarehouseStatus(StatusEnum.DELETE.getValue());
            list.add(warehouse);
        }
        return this.updateBatchById(list, idList.size());
    }

    @Override
    public List<WarehouseVO> listWarehouseVo(WarehouseQuery queryParams) {
        LambdaQueryWrapper<Warehouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Warehouse::getWarehouseStatus, queryParams.getWarehouseStatus() == null ? StatusEnum.ENABLE.getValue() : queryParams.getWarehouseStatus());
        queryWrapper.like(StringUtils.isNotBlank(queryParams.getWarehouseSn()), Warehouse::getWarehouseSn, queryParams.getWarehouseSn());
        queryWrapper.like(StringUtils.isNotBlank(queryParams.getWarehoustName()), Warehouse::getWarehoustName, queryParams.getWarehoustName());
        queryWrapper.like(StringUtils.isNotBlank(queryParams.getWarehousePhone()), Warehouse::getWarehousePhone, queryParams.getWarehousePhone());
        queryWrapper.like(StringUtils.isNotBlank(queryParams.getContact()), Warehouse::getContact, queryParams.getContact());
        queryWrapper.eq(StringUtils.isNotBlank(queryParams.getProvince()), Warehouse::getProvince, queryParams.getProvince());
        queryWrapper.eq(StringUtils.isNotBlank(queryParams.getCity()), Warehouse::getCity, queryParams.getCity());
        queryWrapper.eq(StringUtils.isNotBlank(queryParams.getDistrct()), Warehouse::getDistrct, queryParams.getDistrct());
        queryWrapper.eq(StringUtils.isNotBlank(queryParams.getAddress()), Warehouse::getAddress, queryParams.getAddress());
        if (queryParams.getCreateTime() != null && CollectionUtils.isNotEmpty(queryParams.getCreateTime()) && queryParams.getCreateTime().size() == 2) {
            queryWrapper.between( Warehouse::getCreateTime, queryParams.getCreateTime().get(0), queryParams.getCreateTime().get(1));
        }
        List<Warehouse> warehouses = warehouseMapper.selectList(queryWrapper);

        List<WarehouseVO> warehouseVOList = new ArrayList<>();
        for (Warehouse warehouse : warehouses) {
            WarehouseVO warehouseVO = warehouseConverter.toVo(warehouse);
            warehouseVOList.add(warehouseVO);
        }
        return warehouseVOList;
    }
}
